package com.winai.launcher.adapter;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.clj.fastble.BleManager;
import com.ks.projectbasictools.utils.LogUtils;
import com.sdwfqin.cbt.CbtManager;
import com.sdwfqin.cbt.callback.ServiceListenerCallback;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseRecAdapter;
import com.winai.launcher.base.BaseRecViewHolder;
import com.winai.launcher.bean.BluetoothItemBean;
import com.winai.launcher.interfaces.OnBluetoothOperationListener;
import com.winai.launcher.utils.PicassoLoadUtils;
import com.winai.launcher.view.set.IgnoreBluetoothActivity;
import com.winai.launcher.view.set.SetBluetoothActivity;

import java.lang.reflect.Method;
import java.util.Collections;

/**
 * 作者：康少
 * 时间：2019/11/21 0021
 * 说明：内部类——蓝牙item
 */
public class BluetoothItemAdapter extends BaseRecAdapter<BluetoothItemBean, BluetoothItemAdapter.ViewHolder> {
    private Context mContext;
    private boolean showLine;
    private int layoutId;
    private OnBluetoothOperationListener mOnBluetoothOperationListener;

    public BluetoothItemAdapter(Context context, boolean showLine, int layoutId) {
        this.mContext = context;
        this.showLine = showLine;
        this.layoutId = layoutId;
    }

    public void setOnBluetoothOperationListener(OnBluetoothOperationListener mOnBluetoothOperationListener) {
        this.mOnBluetoothOperationListener = mOnBluetoothOperationListener;
    }

    @Override
    public void onHolder(ViewHolder holder, BluetoothItemBean bean, int position) {
        ImageView ivWifi = holder.getView(R.id.iv_wifi);
        TextView bluetoothName = holder.getView(R.id.tv_wifiName);
        ConstraintLayout clLinkState = holder.getView(R.id.cl_linkState);
        TextView linkState = holder.getView(R.id.tv_linkState);
        ImageView imageView = holder.getView(R.id.iv_linkState);
        Switch switchBluetooth = holder.getView(R.id.switch_keyBluetooth);
        View viewLine = holder.getView(R.id.view_line);
        PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(R.mipmap.icon_bluetooth, ivWifi);

        if (viewLine != null) {
            viewLine.setVisibility(showLine ? View.VISIBLE : View.INVISIBLE);
        }
        //连接状态，-1：未连接；0：正在连接；1：已连接；
        BluetoothItemBean.BluetoothState linkStatus = bean.getBluetoothState();
        if (linkStatus == BluetoothItemBean.BluetoothState.LINKING) {
            //连接中
            connecting("正在连接…", linkState, imageView);
            holder.itemView.setOnClickListener(null);
        } else if (linkStatus == BluetoothItemBean.BluetoothState.LINKED) {
            //已连接
            connected("已连接", linkState, imageView, R.mipmap.icon_wifi_linked);
            //蓝牙忽略
            holder.itemView.setOnClickListener(v -> {
                Intent intent = new Intent(mContext, IgnoreBluetoothActivity.class);
                intent.putExtra("bluetoothBean", bean);
                ((SetBluetoothActivity) mContext).startActivity(intent);
            });
        } else if (linkStatus == BluetoothItemBean.BluetoothState.UNLINK || linkStatus == BluetoothItemBean.BluetoothState.UNBOND) {
            //未连接
            connected("未连接", linkState, imageView, R.mipmap.icon_wifi_linked);
            holder.itemView.setOnClickListener(v -> {
                // 连接蓝牙
                if (mOnBluetoothOperationListener != null) {
                    mOnBluetoothOperationListener.connect(bean, linkState, imageView);
                }
            });
        } else if (linkStatus == BluetoothItemBean.BluetoothState.BONDING) {
            //配对中
            connecting("正在配对…", linkState, imageView);
            holder.itemView.setOnClickListener(null);
        } else if (linkStatus == BluetoothItemBean.BluetoothState.BONDED) {
            //已配对
            connected("已连接", linkState, imageView, R.mipmap.icon_wifi_unlinked);
            //蓝牙忽略
            holder.itemView.setOnClickListener(v -> {
                Intent intent = new Intent(mContext, IgnoreBluetoothActivity.class);
                intent.putExtra("bluetoothBean", bean);
                ((SetBluetoothActivity) mContext).startActivity(intent);
            });
        }
        //蓝牙名称
        bluetoothName.setText(bean.getBluetoothName());
        //蓝牙开关监听
        if (switchBluetooth != null) {
            switchBluetooth.setChecked(BleManager.getInstance().isBlueEnable());
            switchBluetooth.setOnCheckedChangeListener((buttonView, isChecked) -> {
                toggleBluetooth(isChecked);
            });
        }
    }

    @Override
    public ViewHolder onCreateHolder() {
        return new ViewHolder(getViewByRes(layoutId));
    }

    /**
     * 说明：展示加载中，配对中/正在连接
     */
    private void connecting(String linkStateStr, TextView linkState, ImageView imageView) {
        //showLoading
        linkState.setText(linkStateStr);
        linkState.setTextColor(mContext.getResources().getColor(R.color.colorPrimary));
        imageView.setImageResource(R.mipmap.icon_wifi_linking);
        Animation myAlphaAnimation = AnimationUtils.loadAnimation(mContext, R.anim.anim_loading);
        myAlphaAnimation.setInterpolator(new LinearInterpolator());
        //子线程执行动画效果
        new Thread(() -> imageView.startAnimation(myAlphaAnimation)).start();
    }

    /**
     * 说明：完成加载中，已配对/未连接/已连接
     */
    private void connected(String linkStateStr, TextView linkState, ImageView imageView, int ivLayoutId) {
        if (linkState != null) {
            linkState.setText(linkStateStr);
            linkState.setTextColor(Color.parseColor("#585858"));
        }
        if (imageView != null) {
            imageView.setImageResource(ivLayoutId);
            imageView.clearAnimation();
        }
    }

    /**
     * 说明：置顶
     */
    public void onTop(BluetoothDevice device) {
        int pos = -1;
        for (int i = 0; i < getData().size(); i++) {
            if (getData().get(i).getDevice().getMac().equals(device.getAddress())) {
                pos = i;
                break;
            }
        }
        if (pos == -1) {
            return;
        }
        Collections.swap(getData(), pos, 0);
        notifyDataSetChanged();
    }

    /**
     * Desc 切换蓝牙开关
     */
    private void toggleBluetooth(boolean isOpen) {
        if (isOpen) {
            BleManager.getInstance().enableBluetooth();
            setDiscoverableTimeout(300);
            //开启蓝牙服务端
            CbtManager.getInstance().startServiceListener(new ServiceListenerCallback() {
                @Override
                public void onStartError(Throwable throwable) {
                    LogUtils.e("启动蓝牙服务失败，errMsg = " + throwable.getMessage());
                }

                @Override
                public void onDataListener(String s, BluetoothDevice device) {
                    LogUtils.i("启动蓝牙服务成功，s = " + s + ";deviceName = " + device.getName() + ";deviceAddress = " + device.getAddress());
                }
            });
        } else {
            BleManager.getInstance().disableBluetooth();
            try {
                /*关闭服务*/
                CbtManager.getInstance().closeService();
                CbtManager.getInstance().onDestroy();
                /*停止扫描*/
                BleManager.getInstance().cancelScan();
                CbtManager.getInstance().onScanStop();
            } catch (Exception e) {
                e.printStackTrace();
            }
            closeDiscoverableTimeout();
        }
    }
    /**
     * 说明：设置设备蓝牙永久可被发现
     */
    private void setDiscoverableTimeout(int timeout) {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        try {
            Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
            setDiscoverableTimeout.setAccessible(true);
            Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
            setScanMode.setAccessible(true);
            setDiscoverableTimeout.invoke(adapter, timeout);
            setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, timeout);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void closeDiscoverableTimeout() {
        setDiscoverableTimeout(1);
    }

    class ViewHolder extends BaseRecViewHolder {
        ViewHolder(View itemView) {
            super(itemView);
        }
    }
}
